package com.zzyl.intercept;

import cn.hutool.core.util.ObjectUtil;
import com.zzyl.constant.Constants;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    /**
     * 目标方法执行之前 执行的拦截
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 拦截器处理器
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 判断当前被拦截下来的请求 是否是一个后端请求
        if(!(handler instanceof HandlerMethod)){
            //前端的html css js 等不需要校验的前端资源的请求
            return true;
        }
        //2. 从请求头中获取token
        String token = request.getHeader(Constants.USER_TOKEN);

        //3. 判断token是否为空 如果为空则返回401
        if(ObjectUtil.isEmpty(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //4. 如果不为空则解析token 如果解析错误 则返回401
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        if(claims == null){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //5. 从解析的token数据中获取用户的id 如果没有获取到 则返回401
        Integer userId = (Integer)claims.get("id");

        //6. 把userId 存储到线程的副本中
        UserThreadLocal.setSubject(userId+"");

        return true;
    }

    /**
     * 目标方法执行之后 执行的业务 - 清除ThreadLocal中的数据
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清除ThreadLocal中的数据
        UserThreadLocal.removeSubject();
    }
}
